package org.example.com.zwh.schedyled;

import org.example.com.zwh.entity.Product;
import org.example.com.zwh.mapper.ProductStockMapper;
import org.example.com.zwh.service.ProductStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Component
public class stockReconciliation {
    @Autowired
    private ProductStockService productStockService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
//    @Scheduled(cron = "0 0 3 * * ?")//每天3点执行每天三点
    @Scheduled(cron = "* 0/10 * * * ?") // 每10秒执行一次
    public void reconcileStock() {
        System.out.println("库存对账任务开始执行---------------------------");
        //数据库读取库存
        List<Product> products = productStockService.getAllStocks();
        if (products == null) {
            throw new RuntimeException("库存操作失败");
        }
        //redis读取库存
        products.forEach(product -> {
            String key = "seckill:stock:" + product.getId();
            Integer stock = (Integer) redisTemplate.opsForValue().get(key);
            if (stock == null) {
                //如果不存在，返回失败
                throw new RuntimeException("库存操作失败");
            }
            //比较库存是否一致
            if (!stock.equals(product.getStock())) {
                System.out.println("不一致同步数据库");
                System.out.println("redis库存：" + stock);
                System.out.println("数据库库存：" + product.getStock());
                //不一致则修改数据库库存
                int i = productStockService.updateStockNow(stock, product.getId());

                if (i > 0) {
                    System.out.println("库存修改成功");
                }
            }
            //一致则不做修改
            else {
                System.out.println("库存一致");
            }
        });


    }


}
